<script setup lang='ts'>
import type { VxeGridProps } from 'vxe-table'

import { useStoreDict } from '@/store/modules/dict'
import { useGetCategoryTree } from '@fl/api/mall-api'
import { useAddSave, useGetPricPage, usePricDel } from '@fl/api/man-api/pricing-tool'
import { SearchForm, SearchTable } from '@fl/components'
import ButtonItem from '@fl/components/button-item.vue'
import { cloneDeep } from 'lodash-es'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'

import { btns, initPage } from './constant'

const { init } = useStoreDict()
init(['jc_zjgj_boolean', 'jc_zjgj_unit', 'jc_zjgj_input_type', 'jc_zjgj_calc_type', 'jc_zjgj_type'])

const router = useRouter()
const caderRef = ref()
const addDiglog = ref(false)
const initState = { categoryId: '' }

const tablePage = ref(cloneDeep(initPage))
const state = ref(cloneDeep(initState))
const addForm = ref<any>(cloneDeep(initState))

const params = computed(() => ({
    ...state.value,
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
}))

const { data, isLoading, refetch } = useGetPricPage(params)

// 查询类目
const { data: treeData } = useGetCategoryTree()

const searchCol = [
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
            props: {
                checkStrictly: true,
                emitPath: false,
                expandTrigger: 'hover',
                filterable: true,
                label: 'categoryName',
                value: 'id',
            },
            showAllLevels: false,
        },
        label: '组合商品类目',
        options: treeData,
        prop: 'categoryId',
        valueType: 'cascader',
    },
]

const addCol = [
    {
        label: '类目名称',
        prop: 'categoryName',
        valueType: 'select',
    },
]

const rules = {
    categoryName: [{ message: '请选择类目名称', required: true, trigger: 'blur' }],
}

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        // { field: 'categoryName', title: '类目名称' },
        { field: 'rawPathText', title: '组合商品类目' },
        { field: 'createTime', title: '创建日期' },
        { slots: { default: 'operate' }, title: '操作', width: 250 },
    ],
    height: 550,
    rowConfig: {
        keyField: 'id',
    },
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

function doAction(item: any, row: any) {
    switch (item.value) {
        case 'edit':
            goConfig(row.id)
            break
        case 'delete':
            doDel(row.id)
            break
        default:
            break
    }
}

const { mutate } = usePricDel()
function doDel(categoryId: any) {
    mutate({ categoryId }, {
        onSuccess: () => {
            afterSuccess()
        },
    })
}

function afterSuccess() {
    ElMessage({ message: '操作成功', type: 'success' })
    refetch()
}

// 类目配置
function goConfig(id?: string) {
    const str = `/operations-pages/pricing-tool/basic-config${id ? `?id=${id}` : ''}`
    router.push(str)
}

// 计算项
function goCalc() {
    router.push('/operations-pages/pricing-tool/calc-item')
}

function getData(val: any) {
    tablePage.value.currentPage = 1
    state.value = {
        ...state.value,
        ...val,
    }
}

function reset() {
    state.value = cloneDeep(initState)
    tablePage.value = cloneDeep(initPage)
}

function doAdd() {
    addForm.value = cloneDeep(initState)

    addDiglog.value = true
}

const { mutate: mutateAdd } = useAddSave()
function addSave() {
    const target = caderRef.value.getCheckedNodes()
    const { categoryName, categoryPath, id, parentId } = target[0].data

    mutateAdd({
        categoryName,
        parentId,
        path: '0',
        rawId: id,
        rawPath: categoryPath,
        rawPathText: addForm.value.categoryName.join('/'),
        // sort: 1,
    }, {
        onSuccess: () => {
            addDiglog.value = false
            afterSuccess()
        },
    })
}

watchEffect(() => {
    if (data.value) {
        tablePage.value.total = data.value.total
    }
})
</script>

<template>
    <el-card class="mb-20">
        <SearchForm v-bind="state"
                    :columns="searchCol"
                    submit-text="查询"
                    class="mb-20"
                    @submit="getData"
                    @reset="reset"
        />
    </el-card>

    <el-card>
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :data="data?.records"
        >
            <template #toolbar_buttons>
                <el-button v-loading.fullscreen.lock="isLoading"
                           type="primary"
                           @click="doAdd"
                >
                    + 新建
                </el-button>

                <el-button @click="goCalc">
                    计算项配置
                </el-button>
            </template>

            <template #operate="{ row }">
                <div class="text-#dA0004 flex gap-15 justify-center">
                    <ButtonItem :btns="btns"
                                :permission="row.noticeState"
                                @btn-click="doAction($event, row)"
                    />
                </div>
            </template>
        </SearchTable>
    </el-card>

    <!-- 类目新增编辑弹框 -->
    <PlusDialogForm v-model:visible="addDiglog"
                    v-model="addForm"
                    :title="addForm?.id ? '编辑' : '新增'"
                    width="500"
                    :form="{ columns: addCol, rules, labelWidth: 100 }"
                    @confirm="addSave"
    >
        <template #plus-field-categoryName>
            <el-cascader ref="caderRef"
                         v-model="addForm.categoryName"
                         class="w-full"
                         :disabled="addForm?.id"
                         :options="treeData"

                         clearable
                         filterable
                         :props="{ expandTrigger: 'hover', label: 'categoryName', value: 'categoryName', checkStrictly: true }"
            />
        </template>
    </PlusDialogForm>
</template>
